package br.com.fumec.util;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.ws.Service;

public class MazeConnection {

	public String getState(String endpoint) throws SOAPException, MalformedURLException {
		URL url = new URL(endpoint + "?wsdl");

		// Qualified name of the service:
		// 1st arg is the service URI
		// 2nd is the service name published in the WSDL
		QName qname = new QName("http://maze.ia.fumec.br/",
				"TestMazeServerService");
		// Create, in effect, a factory for the service.
		Service service = Service.create(url, qname);
		// Extract the endpoint interface, the service "port".
		IEndpointMazeServer eif = service.getPort(IEndpointMazeServer.class);

		return eif.getState();
	}

	private String getMoveString(Movements m) {
		switch (m) {
		case UP:
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<move>"
					+ "<up/>" + "</move>";
		case DOWN:
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<move>"
					+ "<down/>" + "</move>";
		case RIGHT:
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<move>"
					+ "<right/>" + "</move>";
		case LEFT:
			return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<move>"
					+ "<left/>" + "</move>";
		default:
			return null;

		}
	}

	public String move(String endpoint, Movements m) throws SOAPException, MalformedURLException {
		URL url = new URL(endpoint + "?wsdl");

		// Qualified name of the service:
		// 1st arg is the service URI
		// 2nd is the service name published in the WSDL
		QName qname = new QName("http://maze.ia.fumec.br/",
				"TestMazeServerService");
		// Create, in effect, a factory for the service.
		Service service = Service.create(url, qname);
		// Extract the endpoint interface, the service "port".
		IEndpointMazeServer eif = service.getPort(IEndpointMazeServer.class);

		return eif.move(getMoveString(m));
	}
}